package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mapper.*;
import com.example.pojo.*;
import com.example.service.ILabourContractService;
import com.example.util.DateUtils;
import com.example.util.IdUtils;
import com.example.vo.per.LContractByAll;
import com.example.vo.respvo.IHandleSendOffice;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 劳动合同表 服务实现类
 * </p>
 *
 * @author wsl
 * @since 2022-04-24
 */
@Service
public class LabourContractServiceImpl extends ServiceImpl<LabourContractMapper, LabourContract> implements ILabourContractService {

    @Autowired
    private LabourContractMapper lcm;
    @Autowired
    private ResumeMapper rm;
    @Autowired
    private ResumeClassifyMapper rcm;
    @Autowired
    private DeptMapper dm;
    @Autowired
    private EmpMapper em;
    @Autowired
    private PositionMapper pm;
    @Autowired
    private JobDemandMapper jdm;

    @Override
    public PageInfo<Map<String,Object>> selAllPage(LContractByAll lcba) {
        System.err.println(lcba + "  ------ >");
        PageHelper.startPage(lcba.getPageNum(), lcba.getPageSize());
        List<Map<String, Object>> list = lcm.selByAll(lcba);

        list.forEach(o->{
            o.forEach((a,b) -> {
                try {
                    Integer date = DateUtils.getCompareDate(o.get("end_date").toString());
                    if (date < 0){
                        // 未签署合同
                        uptByLc(Integer.valueOf(o.get("lcId").toString()));
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
        });

        if (!list.isEmpty()){
            return new PageInfo<>(list);
        }
        return null;
    }

    @Override
    public Integer uptByLc(Integer lid) {
        LabourContract contract = new LabourContract();
        contract.setId(lid);
        contract.setStatus(2);
        if (lcm.updateById(contract) > 0){
         return 0;
        }
        return 1;
    }

    @Override
    public List<Map<String,Integer>> transfercountByLcm() {
        List<Map<String,Integer>> list = lcm.countByLcm();
        if (!list.isEmpty()){
            return list;
        }
        return null;
    }

    /**
     * 签订合同 、 合同续签
     * @param labourContract 合同实体类
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer confirmRenew(LabourContract labourContract) {
        selTreeInsEmp(labourContract.getResumeId());
        lcm.updateById(labourContract);
        return 1;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer selTreeInsEmp(Integer resumeId) {
        Resume resume = rm.selectById(resumeId);
        System.err.println("简历id -> "+ resume.getId());
        // 判断员工是否已存在
        Emp one = em.selectOne(new QueryWrapper<Emp>().eq("resume_id", resume.getId()));
        System.err.println("判断员工是否已存在 --- > " + one);
        if (one == null){
            Emp emp = new Emp();
            emp.setEmpName(resume.getName());
            emp.setPhone(resume.getContactPhone());
            emp.setResumeId(resume.getId());
            emp.setHireDate(LocalDate.now());
            // 查询简历
            ResumeClassify classify = rcm.selectOne(new QueryWrapper<ResumeClassify>().eq("resume_id", resume.getId()));
            emp.setPositionId(classify.getPositionId());
            emp.setSuperiorId(classify.getPositionId());
            // 根据岗位编号查询部门
            Position position = pm.selectById(classify.getPositionId());
            // 更改 需求计划
            JobDemand demand = jdm.selectOne(new QueryWrapper<JobDemand>().eq("position_id", position.getId()));
            if (demand.getNum() - 1 == 0){
                demand.setStatus(2);
            }
            demand.setNum(demand.getNum() - 1);
            jdm.updateById(demand);
            // 获取部门信息
            Dept dept = dm.selectById(position.getDeptId());
            emp.setDeptId(dept.getId());
            emp.setSuperiorId(dept.getPrincipalId());
            emp.setWorkId(new IdUtils().getIncreaseIdByNanoTime());

            System.err.println("emp -> " + emp);
            return em.insert(emp);
        }
        return 0;
    }

    @Override
    public Integer insertLc(IHandleSendOffice ihso) {
        LabourContract lc = new LabourContract();
        String byNanoTime = new IdUtils().getIncreaseIdByNanoTime();
        lc.setProcessId("RZHT-" + byNanoTime);
        LocalDate st = LocalDate.parse(ihso.getContractDate()[0], DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate et = LocalDate.parse(ihso.getContractDate()[1], DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        lc.setStartDate(st);
        lc.setEndDate(et);
        LocalDate std = LocalDate.parse(ihso.getTrialDate()[0], DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate etd = LocalDate.parse(ihso.getTrialDate()[1], DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        lc.setProbationStartDate(std);
        lc.setProbationEndDate(etd);
        lc.setPrositionId(ihso.getJobNumber());
        lc.setResumeClassId(ihso.getRcId());
        lc.setMonthWage(new BigDecimal(ihso.getSalary()));

        return lcm.insert(lc);
    }


}
